package middleware

import (
	"github.com/zeromicro/go-zero/rest/httpx"
	"market/api/internal/types"
	"market/pkg"
	"net/http"
)

type UserLoginMiddleware struct {
}

func NewUserLoginMiddleware() *UserLoginMiddleware {
	return &UserLoginMiddleware{}
}

func (m *UserLoginMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation
		token := r.Header.Get("token")
		if token == "" {
			resp := &types.Response{
				Message: "登录为空",
				Code:    500,
				Data:    nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		getToken, s := pkg.GetToken(token)
		if s != "" {
			resp := &types.Response{
				Message: s,
				Code:    200,
				Data:    nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		userid := getToken["userid"].(string)
		r.ParseForm()
		r.Form.Set("userid", userid)
		// Passthrough to next handler if need
		next(w, r)
	}
}
